package com.bbs.core.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bbs.core.common.Const;
import com.bbs.core.common.WebUtils;
import com.bbs.core.model.Module;
import com.bbs.core.model.Topic;
import com.bbs.core.model.User;
import com.bbs.core.service.ModuleService;
import com.bbs.core.service.TopicService;
@Controller
public class BBSController {
	@Autowired
	private TopicService topicService;
	
	@Autowired
	private ModuleService moduleService;

	@Autowired
	private WebUtils webUtils;
	
	static String filePath = null;
	static {
		filePath = System.getProperty("user.dir");
		File file = new File("upload",filePath);
		if(!file.exists()){
			file.mkdirs();
		}
		
	}

	@RequestMapping("/bbs/share")
	public ModelAndView share(HttpServletRequest request){
		return new ModelAndView( "forward:/bbs/topic/module/1-1.html");
	}
	
	@RequestMapping("/")
	public ModelAndView index(HttpServletRequest request){
		return new ModelAndView( "forward:/bbs/index/1.html");
		
	}

	@RequestMapping("/bbs/index/{p}.html")
	public ModelAndView  index(@PathVariable int p,String keyword,HttpServletRequest request,HttpServletResponse response){
		ModelAndView view = new ModelAndView();
		if (StringUtils.isBlank(keyword)) {
			view.setViewName("index");
			//因为用了spring boot缓存,sb是用返回值做缓存,所以service再次返回了pageQuery以缓存查询结果
			List<Topic> findTopicsByPage = topicService.findTopicsByPage(p,Const.TOPIC_PAGE_SIZE);
			List<Module> modules = moduleService.findAllModules();
			User currentUser = webUtils.currentUser(request, response);
			if(currentUser != null){
				Integer mcount = topicService.queryMyMessageTopicCount(currentUser.getId());
				view.addObject("mcount", mcount);
			}
			view.addObject("topicPage", findTopicsByPage);
			view.addObject("modules", modules);
			view.addObject("currentUser", currentUser);
			view.addObject("pagename", "首页综合");
			view.addObject("isAdmin", false);
		}/*else{
			
	    	//查询索引
			PageQuery<IndexObject> searcherKeywordPage = this.bbsService.getQueryPage(keyword,p);
			view.setViewName("/lucene/lucene.html");
			view.addObject("searcherPage", searcherKeywordPage);
			view.addObject("pagename", keyword);
			view.addObject("resultnum", searcherKeywordPage.getTotalRow());
		}*/
		return view;
	}
	
	// ============== 上传文件路径：项目根目录 upload
	@RequestMapping("/bbs/upload")
	@ResponseBody
	public Map<String, Object> upload(@RequestParam("editormd-image-file") MultipartFile file, HttpServletRequest request, HttpServletResponse response){
		String rootPath = filePath;
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", false);
		try {
			User user = webUtils.currentUser(request, response);
			if (null == user) {
				map.put("error", 1);
				map.put("msg", "上传出错，请先登录！");
				return map;
			}
			//从剪切板粘贴上传没有后缀名，通过此方法可以获取后缀名
			Matcher matcher = Pattern.compile("^image/(.+)$",Pattern.CASE_INSENSITIVE).matcher(file.getContentType());
			if(matcher.find()){
				String newName = UUID.randomUUID().toString()+System.currentTimeMillis()+"."+matcher.group(1);
				String filePaths = rootPath + "/upload/";
				File fileout = new File(filePaths);
				if(!fileout.exists()){
					fileout.mkdirs();
				}
				FileCopyUtils.copy(file.getBytes(), new File(filePaths+ newName));
				map.put("file_path", request.getContextPath()+"/bbs/showPic/" + newName);
				map.put("msg","图片上传成功！");
				map.put("success", true);
				return map;
			}else{
				map.put("success","不支持的上传文件格式！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "图片上传出错！");
		}
		return map;
	}
	
	@RequestMapping("/bbs/showPic/{path}.{ext}")
	public void showPic(@PathVariable String path, @PathVariable String ext,HttpServletRequest request, HttpServletResponse response){
		String rootPath = filePath;
		
		try {
			String filePath = rootPath + "/upload/" + path+"."+ext;
			FileInputStream fins = new FileInputStream(filePath);
			response.setContentType("image/jpeg");
			FileCopyUtils.copy(fins, response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ;
	}

	
	
	

}
